/*
@auther fenglei
*/
package xxlog

import (
	"context"
	"errors"
	"fmt"
	"go.uber.org/zap"
	"gorm.io/gorm"
	"time"

	"gorm.io/gorm/logger"
)

// GormLogger implements the gorm.io/gorm/logger.Interface
type GormLogger struct {
	LogLevel logger.LogLevel
}

// NewGormLogger creates a new logger for gorm
func NewGormLogger() logger.Interface {
	return &GormLogger{
		LogLevel: logger.Info,
	}
}

// LogMode sets the log level for the logger
func (l *GormLogger) LogMode(level logger.LogLevel) logger.Interface {
	newLogger := *l
	newLogger.LogLevel = level
	return &newLogger
}

// Info logs info messages
func (l *GormLogger) Info(ctx context.Context, msg string, data ...interface{}) {
	if l.LogLevel >= logger.Info {
		XXLog_Logger.Info(fmt.Sprintf(msg, data...))
	}
}

// Warn logs warn messages
func (l *GormLogger) Warn(ctx context.Context, msg string, data ...interface{}) {
	if l.LogLevel >= logger.Warn {
		XXLog_Logger.Warn(fmt.Sprintf(msg, data...))
	}
}

// Error logs error messages
func (l *GormLogger) Error(ctx context.Context, msg string, data ...interface{}) {
	if l.LogLevel >= logger.Error {
		XXLog_Logger.Error(fmt.Sprintf(msg, data...))
	}
}

// Trace logs SQL and execution time
func (l *GormLogger) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error) {
	if l.LogLevel <= logger.Silent {
		return
	}

	elapsed := time.Since(begin)
	sql, rows := fc()

	// Create fields for structured logging
	fields := []zap.Field{
		zap.String("sql", sql),
		zap.Int64("rows", rows),
		zap.Duration("elapsed", elapsed),
	}

	// Handle errors
	if err != nil && !(errors.Is(err, gorm.ErrRecordNotFound)) {
		fields = append(fields, zap.Error(err))
		XXLog_Logger.Error("Gorm Query Error", fields...)
		return
	}
	// Log slow queries as warnings
	//if l.SlowThreshold > 0 && elapsed > l.SlowThreshold && l.LogLevel >= logger.Warn {
	//	l.ZapLogger.Warn("gorm slow query", fields...)
	//	return
	//}

	// Log normal queries as debug/info
	if l.LogLevel >= logger.Info {
		XXLog_Logger.Info("Gorm Query", fields...)
	}
}
